<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true" :model="queryParams" class="form-inline">
        <el-form-item label="用户ID">
          <el-input 
            v-model="queryParams.userId" 
            placeholder="请输入用户ID" 
            clearable 
            type="number"
          />
        </el-form-item>
        <el-form-item label="留言类型">
          <el-select v-model="queryParams.messageType" placeholder="请选择留言类型" clearable>
            <el-option label="文字留言" value="0" />
            <el-option label="图片留言" value="1" />
            <el-option label="文字+图片" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="正常显示" value="0" />
            <el-option label="已隐藏" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <el-table
      v-loading="loading"
      :data="messageList"
      border
      style="width: 100%"
    >
      <el-table-column prop="messageId" label="留言ID" width="80" align="center" />
      <el-table-column prop="userId" label="用户ID" width="80" align="center" />
      <el-table-column prop="userName" label="用户名" width="120" />
      <el-table-column label="用户头像" width="80" align="center">
        <template #default="scope">
          <el-avatar 
            v-if="scope.row.userAvatar" 
            :src="getImageUrl(scope.row.userAvatar)" 
            :size="40"
          />
          <el-avatar v-else :size="40" icon="UserFilled" />
        </template>
      </el-table-column>
      <el-table-column label="留言内容" min-width="200">
        <template #default="scope">
          <div class="message-content">
            <div v-if="scope.row.content" class="content-text">
              {{ scope.row.content }}
            </div>
            <div v-if="scope.row.image" class="content-image">
              <el-image 
                :src="getImageUrl(scope.row.image)" 
                style="width: 60px; height: 60px"
                :preview-src-list="[getImageUrl(scope.row.image)]"
                fit="cover"
              />
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="留言类型" width="100" align="center">
        <template #default="scope">
          <el-tag :type="getMessageTypeTagType(scope.row.messageType)">
            {{ getMessageTypeText(scope.row.messageType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === '0' ? 'success' : 'info'">
            {{ scope.row.status === '0' ? '正常显示' : '已隐藏' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="160" />
      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
          <el-button size="small" @click="handleView(scope.row)">查看详情</el-button>
          <el-button 
            type="danger" 
            size="small" 
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 留言详情对话框 -->
    <el-dialog
      title="留言详情"
      v-model="dialogVisible"
      width="600px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="留言ID">{{ detailForm.messageId }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ detailForm.userId }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{ detailForm.userName }}</el-descriptions-item>
        <el-descriptions-item label="用户头像">
          <el-avatar 
            v-if="detailForm.userAvatar" 
            :src="getImageUrl(detailForm.userAvatar)" 
            :size="60"
          />
          <el-avatar v-else :size="60" icon="UserFilled" />
        </el-descriptions-item>
        <el-descriptions-item label="留言内容">
          <div class="detail-content">{{ detailForm.content || '无文字内容' }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="留言图片" v-if="detailForm.image">
          <el-image 
            :src="getImageUrl(detailForm.image)" 
            style="width: 200px; height: 200px"
            :preview-src-list="[getImageUrl(detailForm.image)]"
            fit="cover"
          />
        </el-descriptions-item>
        <el-descriptions-item label="留言类型">
          <el-tag :type="getMessageTypeTagType(detailForm.messageType)">
            {{ getMessageTypeText(detailForm.messageType) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="detailForm.status === '0' ? 'success' : 'info'">
            {{ detailForm.status === '0' ? '正常显示' : '已隐藏' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailForm.createTime }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button 
            type="danger" 
            @click="handleDeleteFromDetail"
          >
            删除留言
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getMessageWallPage, getMessageWallDetail, deleteMessageWall } from '@/api/messageWall'
import { handlePageResponse } from '@/utils/pagination'

// 留言列表
const messageList = ref([])
// 总数据量
const total = ref(0)
// 加载状态
const loading = ref(false)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  userId: '',
  messageType: '',
  status: ''
})

// 留言详情表单
const detailForm = ref({})
// 留言详情对话框可见性
const dialogVisible = ref(false)

// 获取图片URL
const getImageUrl = (imagePath) => {
  if (!imagePath) return ''
  return `/api/file/download?fileName=${imagePath}`
}

// 获取留言类型文本
const getMessageTypeText = (type) => {
  const typeMap = {
    '0': '文字留言',
    '1': '图片留言',
    '2': '文字+图片'
  }
  return typeMap[type] || '未知类型'
}

// 获取留言类型标签类型
const getMessageTypeTagType = (type) => {
  const typeMap = {
    '0': 'primary',
    '1': 'success',
    '2': 'warning'
  }
  return typeMap[type] || ''
}

// 初始化数据
onMounted(async () => {
  await fetchData()
})

// 获取留言列表数据
const fetchData = async () => {
  loading.value = true
  try {
    const res = await getMessageWallPage(queryParams)
    const { list, total: totalCount } = handlePageResponse(res)
    messageList.value = list
    total.value = totalCount
  } catch (error) {
    console.error('获取留言列表失败:', error)
    ElMessage.error('获取留言列表失败')
  } finally {
    loading.value = false
  }
}

// 处理查询
const handleQuery = () => {
  queryParams.pageNum = 1
  fetchData()
}

// 重置查询
const resetQuery = () => {
  queryParams.userId = ''
  queryParams.messageType = ''
  queryParams.status = ''
  handleQuery()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  fetchData()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  queryParams.pageNum = 1
  fetchData()
}

// 处理查看留言详情
const handleView = async (row) => {
  try {
    const res = await getMessageWallDetail(row.messageId)
    if (res.code === 200) {
      detailForm.value = res.data
      dialogVisible.value = true
    }
  } catch (error) {
    console.error('获取留言详情失败:', error)
    ElMessage.error('获取留言详情失败')
  }
}

// 处理删除留言
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确认要删除用户"${row.userName}"的这条留言吗？此操作将永久删除该留言，无法恢复！`,
    '警告',
    {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteMessageWall(row.messageId)
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
      // 刷新留言列表
      fetchData()
    } catch (error) {
      console.error('删除留言失败:', error)
      ElMessage({
        type: 'error',
        message: '删除失败，请稍后再试'
      })
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}

// 从详情页面删除留言
const handleDeleteFromDetail = () => {
  handleDelete(detailForm.value)
  dialogVisible.value = false
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  padding-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}

.message-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.content-text {
  line-height: 1.5;
  word-break: break-all;
}

.content-image {
  display: flex;
  justify-content: flex-start;
}

.detail-content {
  max-width: 400px;
  line-height: 1.6;
  word-break: break-all;
  white-space: pre-wrap;
}
</style>
